package com.jci.xyf.hellofx.qq;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.jci.xyf.hellofx.mysqlconn;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;

import java.sql.ResultSet;
import java.sql.SQLException;

public class Controller3 {
    @FXML
    private Label qqname;
    @FXML
    private TextField qqTxt;
    @FXML
    private ImageView ima;
    @FXML
    private Label qqtx;
    @FXML
    public void qqselect(ActionEvent actionEvent) {
        //起到一个Loading的效果
        qqname.setText("Loading……");
        String qqVal = qqTxt.getText();
        mysqlconn my = new mysqlconn();
        my.startmysql();
        //异步机制
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                String url = "https://qqlykm.cn/api/qqobtain/get?key=UzU1uxxMaQXeR4R87HRKYT63Cv&qq=" + qqVal;
                String result = HttpUtil.get(url);
                String resulthandle=("{"+result.substring(result.indexOf("nickname")-1));
                System.out.println(resulthandle);
                qqdata qq = JSONUtil.toBean(result, qqdata.class);
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                String sqlexit = "SELECT *\n" + "FROM qqinf\n" + "WHERE nickname='" + qq.getNickname() + "';";
                ResultSet rs = my.query(sqlexit);
                try {
                    if(rs.next()==false){
                        Image image = new Image(qq.getHeadimg());
                        ima.setImage(image);
                        qqtx.setText("QQ头像");
                        qqname.setText("QQ昵称："+qq.getNickname());
                        String name=qq.getNickname();
                        String img=qq.getHeadimg();
                        String sql="insert into qqinf(nickname,heading) values('"+name+"','"+img+"');";
                        my.updata(sql);
                    }else {
                        Image image = new Image(rs.getString("heading"));
                        ima.setImage(image);
                        qqtx.setText("QQ头像");
                        qqname.setText("QQ昵称："+rs.getString("nickname"));
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }

            }
        });
    }
}
